from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from datetime import datetime, timedelta
import random

from app.database import get_db
from app.db_models.user import User
from app.schemas.password_reset import SendVerificationCodeRequest, VerifyCodeRequest, ResetPasswordRequest
from app.schemas.response import Response, ResponseCode
from app.api.auth import get_password_hash
from app.utils.email_utils import generate_verification_code, send_verification_email
from app.utils.verification_cache import save_verification_code, verify_code, mark_code_as_used

router = APIRouter(
    prefix="/user",
    tags=["password_reset"],
    responses={404: {"description": "Not found"}},
)


@router.post("/forgot-password/send-code", response_model=Response)
def send_verification_code(request: SendVerificationCodeRequest, db: Session = Depends(get_db)):
    """发送密码重置验证码
    
    向用户邮箱发送6位数字验证码
    
    Args:
        request: 包含用户邮箱的请求
        db: 数据库会话
        
    Returns:
        Response: 统一响应格式
    """
    try:
        # 查找用户并验证用户名和邮箱是否匹配
        user = db.query(User).filter(
            User.email == request.email,
            User.username == request.username
        ).first()
        if not user:
            return Response.fail(message="用户名或邮箱不正确")
        
        # 生成验证码
        verification_code = generate_verification_code()
        
        # 保存验证码到缓存
        save_verification_code(request.email, verification_code)
        
        # 发送验证码邮件
        email_sent = send_verification_email(user.email, verification_code)
        if not email_sent:
            return Response.fail(message="验证码发送失败，请稍后重试")
        
        return Response.success(message="验证码已发送到您的邮箱")
    except Exception as e:
        return Response.error(message=f"发送验证码失败: {str(e)}")


@router.post("/forgot-password/verify-code", response_model=Response)
def verify_verification_code(request: VerifyCodeRequest, db: Session = Depends(get_db)):
    """验证密码重置验证码
    
    验证用户输入的验证码是否正确
    
    Args:
        request: 包含用户邮箱和验证码的请求
        db: 数据库会话
        
    Returns:
        Response: 统一响应格式
    """
    try:
        # 查找用户并验证用户名和邮箱是否匹配
        user = db.query(User).filter(
            User.email == request.email,
            User.username == request.username
        ).first()
        if not user:
            return Response.fail(message="用户名或邮箱不正确")
        
        # 验证验证码
        if not verify_code(request.email, request.code):
            return Response.fail(message="验证码无效或已过期")
        
        return Response.success(message="验证码验证成功")
    except Exception as e:
        return Response.error(message=f"验证码验证失败: {str(e)}")


@router.post("/forgot-password/reset", response_model=Response)
def reset_password(request: ResetPasswordRequest, db: Session = Depends(get_db)):
    """重置密码
    
    验证验证码并重置用户密码
    
    Args:
        request: 包含用户邮箱、验证码和新密码的请求
        db: 数据库会话
        
    Returns:
        Response: 统一响应格式
    """
    try:
        # 验证密码
        if request.new_password != request.confirm_password:
            return Response.fail(message="两次输入的密码不匹配")
        
        # 查找用户
        user = db.query(User).filter(User.email == request.email).first()
        if not user:
            return Response.fail(message="该邮箱未注册")
        
        # 验证验证码
        if not verify_code(request.email, request.code):
            return Response.fail(message="验证码无效或已过期")
        
        # 更新密码
        user.password = get_password_hash(request.new_password)
        
        # 标记验证码为已使用
        mark_code_as_used(request.email)
        
        db.commit()
        
        return Response.success(message="密码重置成功")
    except Exception as e:
        db.rollback()
        return Response.error(message=f"密码重置失败: {str(e)}")